package com.mantru.iotpot.dishes

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.KeyEvent
import android.view.inputmethod.InputMethodManager
import android.widget.TextView
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.distinctUntilChanged
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.mantru.iotpot.Adapter.DishesShowAdapter
import com.mantru.iotpot.R
import com.mantru.iotpot.Tools.LoadingDialogUtil
import com.mantru.iotpot.databinding.ActivityDishesShowBinding

class DishesShowActivity : AppCompatActivity() {
    private val viewModel by viewModels<DishesShowViewModel>()
    private lateinit var binding: ActivityDishesShowBinding
    //adapter属于UI层，负责交互，留在Activity
    private var dishesShowAdapter: DishesShowAdapter? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_dishes_show)
        binding.viewModel = viewModel // 绑定viewModel
        binding.lifecycleOwner = this // 允许 LiveData 自动更新 UI

        //初始化recyclerview
        setRecyclerView()
        //设置控件交互事件
        setContentAction()
        //观察者模式，观察dishesList变化，更新adapter数据
        setupObservers()
    }

    override fun onResume() {
        super.onResume()
        //获取菜谱数据
        val map: MutableMap<String, Any> = HashMap()
        map["type"] = 3
        map["data"] = ""
        map["count"] = 10000
        map["char"] = ""
        viewModel.getHttpValue("GetSQLData_Vegetable_Search", map)
        // 在界面渲染完成后发送广播关闭弹窗
        Handler(Looper.getMainLooper()).post {
            val intent = Intent("ACTION_CLOSE_LOADING_DIALOG")
            LocalBroadcastManager.getInstance(this@DishesShowActivity).sendBroadcast(intent)
        }
    }

    //初始化recyclerview
    private fun setRecyclerView(){
        dishesShowAdapter = DishesShowAdapter(this, R.layout.adapter_dishes_picture, viewModel.dishesList.value ?: mutableListOf())
        binding.dishesShowRecyclerview.apply {
            setLayoutManager(StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL))
            adapter = dishesShowAdapter
        }
    }

    //设置控件交互事件
    private fun setContentAction(){

        //搜索按钮
        binding.dishesShowSearch.setOnClickListener{
            //获取搜索内容菜谱
            //如果是空的，就获取所有数据，否则获取指定数据
            if ( viewModel.dishesSearch.get().toString().isEmpty() ){
                val map: MutableMap<String, Any> = HashMap()
                map["type"] = 3
                map["data"] = ""
                map["count"] = 10000
                map["char"] = ""
                viewModel.getHttpValue("GetSQLData_Vegetable_Search", map)
            } else {
                val map: MutableMap<String, Any> = HashMap()
                map["type"] = 3
                map["data"] = viewModel.dishesSearch.get().toString()
                map["count"] = 10000
                map["char"] = ""
                viewModel.getHttpValue("GetSQLData_Vegetable_Search", map)
            }
        }

        //关闭按钮
        binding.dishesShowBack.setOnClickListener {
            LoadingDialogUtil.showLoadingDialog(this@DishesShowActivity)
            finish()
        }

        //刷新按钮
        binding.dishesShowRefresh.setOnClickListener {
            //获取搜索内容菜谱
            //如果是空的，就获取所有数据，否则获取指定数据
            if ( viewModel.dishesSearch.get().toString().isEmpty() ){
                val map: MutableMap<String, Any> = HashMap()
                map["type"] = 3
                map["data"] = ""
                map["count"] = 10000
                map["char"] = ""
                viewModel.getHttpValue("GetSQLData_Vegetable_Search", map)
            } else {
                val map: MutableMap<String, Any> = HashMap()
                map["type"] = 3
                map["data"] = viewModel.dishesSearch.get().toString()
                map["count"] = 10000
                map["char"] = ""
                viewModel.getHttpValue("GetSQLData_Vegetable_Search", map)
            }
        }

        //新建菜品按钮
        binding.dishesShowNew.setOnClickListener {
            val intent = Intent(this@DishesShowActivity, DishesListActivity::class.java)
            startActivity(intent)
        }

        //菜谱录制按钮
        binding.dishesShowRecord.setOnClickListener {
            val intent = Intent(this@DishesShowActivity, DishesRecordSetActivity::class.java)
            startActivity(intent)
        }

        //adapter交互
        dishesShowAdapter!!.setDishesShowListener(object : DishesShowAdapter.DishesShowListener{
            override fun onClick(position: Int) {
                if ( viewModel.idList.get()!!.size > position ){
                    val intent = Intent(this@DishesShowActivity, DishesCreateActivity::class.java)
                    intent.putExtra("vegetableId", viewModel.idList.get()!![position].toInt())
                    startActivity(intent)
                }
            }
        })

        //监听输入框回车按键
        binding.dishesShowEdittext.setOnEditorActionListener { v: TextView, actionId: Int, event: KeyEvent? ->
            // 检查是否是按下 Enter 键或者完成操作
            if ((event != null && event.action == KeyEvent.ACTION_DOWN && event.keyCode == KeyEvent.KEYCODE_ENTER)
                || actionId == android.view.inputmethod.EditorInfo.IME_ACTION_DONE
                || actionId == android.view.inputmethod.EditorInfo.IME_ACTION_NEXT
                || actionId == android.view.inputmethod.EditorInfo.IME_ACTION_SEND) {

                // 获取输入法管理器
                val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager?
                // 隐藏软键盘
                imm?.hideSoftInputFromWindow(v.windowToken, 0)
                return@setOnEditorActionListener true
            }
            return@setOnEditorActionListener false
        }
    }

    //观察者模式，观察dishesList变化，更新adapter数据
    private fun setupObservers() {
        viewModel.dishesList
            .distinctUntilChanged() // 过滤相同数据
            .observe(this) { list ->
                list?.let {
                    dishesShowAdapter?.updateData(it)
                }
            }
    }

    // 在SettingActivity中注册和注销广播接收器
    private val receiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            if (intent.action == "ACTION_CLOSE_LOADING_DIALOG") {
                LoadingDialogUtil.closeLoadingDialog()
            }
        }
    }

    override fun onStart() {
        super.onStart()
        LocalBroadcastManager.getInstance(this).registerReceiver(receiver, IntentFilter("ACTION_CLOSE_LOADING_DIALOG"))
    }

    override fun onStop() {
        super.onStop()
        LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver)
    }

}